from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify
from exts import mail, db
from flask_mail import Message
import string
import random
from models import EmailCaptchaModel, UserModel
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint("auth", __name__, url_prefix="/auth")


@bp.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("用户不存在")
                return redirect(url_for("auth.login"))
            if check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect('/')
                # return "登录成功"
            else:
                print("密码错误")
                return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.login"))


@bp.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "GET":
        return render_template("register.html")
    else:
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(username=username, password=generate_password_hash(password), email=email)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.register"))


# http://127.0.0.1:5000/auth/captcha/email?email=2097969685@qq.com
@bp.route("/captcha/email", methods=["POST"])
def get_captcha():
    email = request.args.get("email")
    source = random.sample(string.digits * 4, 4)
    captcha = "".join(source)
    message = Message(subject="注册验证码", sender="2949666522@qq.com", recipients=[email],
                      body=f"您的邮箱验证码为：{captcha}，有效期1分钟。")
    mail.send(message)
    email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    return jsonify({"code": 200, "message": "", "data": ""})


@bp.route("/mail/test/")
def send_mail():
    message = Message(subject="Hello", sender="2949666522@qq.com", recipients=["2097969685@qq.com"],
                      body="This is a test email.")
    mail.send(message)
    return "Mail sent successfully!"


@bp.route("/logout")
def logout():
    session.clear()
    return redirect(url_for('auth.login'))
